package com.huaguoguo.spring.context;

import com.huaguoguo.spring.annotation.Bean;
import com.huaguoguo.spring.annotation.Configuration;
import com.huaguoguo.spring.context.config.BeanDefinition;
import com.huaguoguo.spring.context.config.ConfigurBeanDefinition;
import com.huaguoguo.spring.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

public class ConfigurationBeanLoad {

    public void beanload(Map<String, Object> beanMap, Class<?> aClass, Map<String,DelayLoadBean> delayLoadBeanMap){
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            Bean beanAnnotation = method.getAnnotation(Bean.class);
            if (beanAnnotation != null) {
                DelayLoadBean delayLoadBean = new DelayLoadBean();
                // bean优先取@Bean注解中的value，若为空取方法名
                String beanName = StringUtils.isNotEmpty(beanAnnotation.value()) ? beanAnnotation.value() : method.getName();
                delayLoadBean.setBeanName(beanName);
                delayLoadBean.setMethod(method);
                // 配置类名称同理
                String configBeanName = aClass.getAnnotation(Configuration.class).value();
                configBeanName =  StringUtils.isNotEmpty(configBeanName)?configBeanName:StringUtils.toLowerCaseFirstOne(aClass.getSimpleName());
                delayLoadBean.setBelongConfigBeanName(configBeanName);
                delayLoadBeanMap.put(beanName,delayLoadBean);
            }

        }
    }

    public void beanload(RegisterBeanDefinition registerBeanDefinition, Class<?> aClass) {
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            Bean beanAnnotation = method.getAnnotation(Bean.class);
            if (beanAnnotation != null) {
                // bean优先取@Bean注解中的value，若为空取方法名
                String beanName = StringUtils.isNotEmpty(beanAnnotation.value()) ? beanAnnotation.value() : method.getName();
                ConfigurBeanDefinition beanDefinition = new ConfigurBeanDefinition();
                beanDefinition.setBeanName(beanName);
                beanDefinition.setBeanType(method.getReturnType());

                // 获取配置类的beanName
                String configBeanName = aClass.getAnnotation(Configuration.class).value();
                configBeanName =  StringUtils.isNotEmpty(configBeanName)?configBeanName:StringUtils.toLowerCaseFirstOne(aClass.getSimpleName());
                beanDefinition.setParentBeanName(configBeanName);
                beanDefinition.setMethod(method);
                registerBeanDefinition.beanDefinitionMap.put(beanName,beanDefinition);
            }

        }
    }
}
